<script setup>
import { reactive, ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';

// 定义props和emits
const props = defineProps({
  onSwitchToLogin: Function
});

const emit = defineEmits(['register-success']);

// 路由器和auth store
const router = useRouter();
const authStore = useAuthStore();

// 表单状态
const formData = reactive({
  username: '',
  email: '',
  password: '',
  firstName: '',
  lastName: '',
  gender: '',
  preferredLanguage: 'zh'
});

// 错误信息
const errors = reactive({
  username: '',
  email: '',
  password: '',
  firstName: '',
  lastName: '',
  gender: '',
  preferredLanguage: '',
  general: ''
});

// 加载状态
const loading = ref(false);

// 邮箱验证正则
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// 密码可见性控制
const passwordVisible = ref(false);

const togglePasswordVisibility = () => {
  passwordVisible.value = !passwordVisible.value;
};

// 表单验证
const validateForm = () => {
  let isValid = true;
  
  // 重置错误
  errors.username = '';
  errors.email = '';
  errors.password = '';
  errors.firstName = '';
  errors.lastName = '';
  errors.gender = '';
  errors.preferredLanguage = '';
  errors.general = '';
  
  // 用户名验证
  if (!formData.username.trim()) {
    errors.username = '请输入用户名';
    isValid = false;
  } else if (formData.username.length < 3) {
    errors.username = '用户名长度不能少于3个字符';
    isValid = false;
  }
  
  // 邮箱验证
  if (!formData.email.trim()) {
    errors.email = '请输入邮箱';
    isValid = false;
  } else if (!emailRegex.test(formData.email)) {
    errors.email = '请输入有效的邮箱地址';
    isValid = false;
  }
  
  // 密码验证
  if (!formData.password) {
    errors.password = '请输入密码';
    isValid = false;
  } else if (formData.password.length < 6) {
    errors.password = '密码长度不能少于6个字符';
    isValid = false;
  }
  
  return isValid;
};

// 处理注册逻辑
const handleRegister = async () => {
  // 验证表单
  if (!validateForm()) return;
  
  loading.value = true;
  
  try {
    // 准备请求数据
    const requestData = {
      username: formData.username,
      email: formData.email,
      password: formData.password,
      firstName: formData.firstName,
      lastName: formData.lastName,
      gender: formData.gender,
      preferredLanguage: formData.preferredLanguage
    };
    
    console.log('发送注册请求，数据：', requestData);
    
    // 调用auth store的注册方法
    const result = await authStore.register(requestData);
    
    console.log('注册结果：', result);
    
    if (result.success) {
      console.log('注册成功，用户信息：', authStore.userInfo);
      
      // 发出注册成功事件
      emit('register-success', authStore.userInfo);
      
      // 路由跳转到首页
      router.push('/');
    } else {
      // 处理字段特定的错误
      if (result.field === 'username') {
        errors.username = result.message || '用户名已被使用';
      } else if (result.field === 'email') {
        errors.email = result.message || '邮箱已被使用';
      } else {
        errors.general = result.message || '注册失败，请稍后再试';
      }
    }
  } catch (err) {
    console.error('注册处理错误:', err);
    errors.general = '注册过程中发生错误，请稍后再试';
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <div class="register-form">
    <!-- 错误信息提示 -->
    <div v-if="errors.general" class="error-message general">
      <i class="fas fa-exclamation-circle"></i> {{ errors.general }}
    </div>
    
    <form @submit.prevent="handleRegister">
      <!-- 用户名 -->
      <div class="form-group">
        <label for="register-username">用户名</label>
        <div class="input-group">
          <i class="fas fa-user"></i>
          <input 
            id="register-username" 
            v-model="formData.username" 
            type="text" 
            placeholder="请输入用户名" 
            :class="{ 'error': errors.username }"
          >
        </div>
        <div v-if="errors.username" class="error-message">
          {{ errors.username }}
        </div>
      </div>
      
      <!-- 姓名 -->
      <div class="form-row two-columns">
        <div class="form-group">
          <label for="firstName">名</label>
          <div class="input-group">
            <i class="fas fa-user-tag"></i>
            <input 
              id="firstName" 
              v-model="formData.firstName" 
              type="text" 
              placeholder="请输入名字" 
              :class="{ 'error': errors.firstName }"
            >
          </div>
          <div v-if="errors.firstName" class="error-message">
            {{ errors.firstName }}
          </div>
        </div>
        
        <div class="form-group">
          <label for="lastName">姓</label>
          <div class="input-group">
            <i class="fas fa-user-tag"></i>
            <input 
              id="lastName" 
              v-model="formData.lastName" 
              type="text" 
              placeholder="请输入姓氏" 
              :class="{ 'error': errors.lastName }"
            >
          </div>
          <div v-if="errors.lastName" class="error-message">
            {{ errors.lastName }}
          </div>
        </div>
      </div>
      
      <!-- 邮箱 -->
      <div class="form-group">
        <label for="register-email">邮箱</label>
        <div class="input-group">
          <i class="fas fa-envelope"></i>
          <input 
            id="register-email" 
            v-model="formData.email" 
            type="email" 
            placeholder="请输入邮箱" 
            :class="{ 'error': errors.email }"
          >
        </div>
        <div v-if="errors.email" class="error-message">
          {{ errors.email }}
        </div>
      </div>
      
      <!-- 密码 -->
      <div class="form-group">
        <label for="register-password">密码</label>
        <div class="input-group">
          <i class="fas fa-lock"></i>
          <input 
            id="register-password" 
            v-model="formData.password" 
            :type="passwordVisible ? 'text' : 'password'" 
            placeholder="请输入密码" 
            :class="{ 'error': errors.password }"
          >
          <i 
            :class="passwordVisible ? 'fas fa-eye' : 'fas fa-eye-slash'" 
            class="toggle-password"
            @click="togglePasswordVisibility"
          ></i>
        </div>
        <div v-if="errors.password" class="error-message">
          {{ errors.password }}
        </div>
      </div>
      
      <!-- 性别与偏好语言 -->
      <div class="form-row two-columns">
        <div class="form-group">
          <label>性别</label>
          <div class="radio-group">
            <label class="radio-label">
              <input type="radio" value="male" v-model="formData.gender">
              <span class="radio-custom"></span>
              <span>男</span>
            </label>
            <label class="radio-label">
              <input type="radio" value="female" v-model="formData.gender">
              <span class="radio-custom"></span>
              <span>女</span>
            </label>
            <label class="radio-label">
              <input type="radio" value="other" v-model="formData.gender">
              <span class="radio-custom"></span>
              <span>其他</span>
            </label>
          </div>
          <div v-if="errors.gender" class="error-message">
            {{ errors.gender }}
          </div>
        </div>
        
        <div class="form-group">
          <label for="language">偏好语言</label>
          <div class="select-wrapper">
            <select id="language" v-model="formData.preferredLanguage">
              <option value="zh">中文</option>
              <option value="en">英文</option>
            </select>
            <i class="fas fa-chevron-down select-arrow"></i>
          </div>
        </div>
      </div>
      
      <!-- 注册按钮 -->
      <button type="submit" class="btn-register" :disabled="loading">
        <i v-if="loading" class="fas fa-spinner fa-spin"></i>
        <span v-else>注册</span>
      </button>
    </form>
  </div>
</template>

<style scoped>
.register-form {
  width: 100%;
  height: 100%;
  max-height: none; /* 移除最大高度限制 */
  overflow-y: visible; /* 移除垂直滚动 */
  padding-right: 0; /* 移除为滚动条预留的空间 */
}

.form-group {
  margin-bottom: 15px; /* 增加表单项之间的间距 */
}

.form-group label {
  display: block;
  margin-bottom: 5px; /* 增加标签与输入框之间的间距 */
  font-weight: 500;
  font-size: 0.9rem;
  color: #333;
}

.form-row {
  display: flex;
  gap: 8px; /* 减少水平间距 */
  margin-bottom: 0;
}

.form-row.two-columns > .form-group {
  flex: 1;
}

.input-group {
  position: relative;
  display: flex;
  align-items: center;
}

/* 输入框左侧图标 */
.input-group i:not(.toggle-password) {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #888;
  font-size: 16px;
}

/* 密码可见性切换图标 */
.input-group .toggle-password {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #888;
  cursor: pointer;
  font-size: 16px;
  z-index: 2;
}

.input-group input, .select-wrapper select {
  width: 100%;
  padding: 12px 40px 12px 40px; /* 增加输入框内边距 */
  border: 1px solid #ccc;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s, box-shadow 0.3s;
  height: 42px; /* 固定高度确保一致性 */
}

.input-group input.no-left-icon {
  padding-left: 15px;
}

.input-group input:focus, .select-wrapper select:focus {
  outline: none;
  border-color: #00c389;
  box-shadow: 0 0 0 3px rgba(0, 195, 137, 0.1);
}

.input-group input.error {
  border-color: #ff5a5a;
}

/* 隐藏浏览器自带的密码显示按钮 */
input[type="password"]::-ms-reveal,
input[type="password"]::-ms-clear {
  display: none;
}

input[type="password"]::-webkit-credentials-auto-fill-button,
input[type="password"]::-webkit-contacts-auto-fill-button {
  visibility: hidden;
  display: none !important;
  pointer-events: none;
  position: absolute;
  right: 0;
}

.select-wrapper {
  position: relative;
}

.select-wrapper select {
  appearance: none;
  padding-right: 30px;
  background-color: white;
}

.select-arrow {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  pointer-events: none;
  color: #888;
}

.radio-group {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  margin-top: 2px; /* 减少单选按钮与标签间距 */
}

.radio-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  gap: 8px;
}

.radio-label input {
  position: absolute;
  opacity: 0;
}

.radio-custom {
  width: 16px; /* 减小单选按钮尺寸 */
  height: 16px;
  border-radius: 50%;
  border: 1px solid #ccc;
  display: inline-block;
  position: relative;
}

.radio-label input:checked ~ .radio-custom::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 8px; /* 减小单选按钮内部圆点尺寸 */
  height: 8px;
  border-radius: 50%;
  background-color: #00c389;
}

.radio-label input:checked ~ .radio-custom {
  border-color: #00c389;
}

.error-message {
  color: #ff5a5a;
  font-size: 0.75rem; /* 缩小错误信息字体 */
  margin-top: 1px; /* 减少错误信息上方间距 */
}

.error-message.general {
  padding: 6px;
  margin-bottom: 8px;
  font-size: 0.75rem;
}

.btn-register {
  width: 100%;
  padding: 12px; /* 增加按钮内边距 */
  background-color: #ff5a5a;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 18px; /* 增加按钮上方间距 */
  height: 45px; /* 固定按钮高度 */
}

.btn-register:hover {
  background-color: #ff3939;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 90, 90, 0.3);
}

.btn-register:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

@media (max-width: 576px) {
  .form-row {
    flex-direction: column;
    gap: 0;
  }
  
  .radio-group {
    gap: 12px;
  }
  
  .input-group input, 
  .select-wrapper select {
    padding: 10px 40px 10px 36px;
    font-size: 14px;
  }
  
  .input-group i:not(.toggle-password),
  .input-group .toggle-password {
    font-size: 14px;
  }
}

/* 移除自定义滚动条样式 */
.register-form::-webkit-scrollbar,
.register-form::-webkit-scrollbar-track,
.register-form::-webkit-scrollbar-thumb,
.register-form::-webkit-scrollbar-thumb:hover {
  display: none;
}
</style> 